<?php

namespace Pw\AccessBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

use Pw\AccessBundle\Entity\User;
use Pw\AccessBundle\Form\Type\UserType;

class SecurityController extends Controller
{
    public function loginAction(){
		if (!$this->getUser()) {
			$request = $this->getRequest();
			$session = $request->getSession();

			$error = '';
			if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
				$error = $request->attributes->has(SecurityContext::AUTHENTICATION_ERROR);
			} else {
				$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
				$session->remove(SecurityContext::AUTHENTICATION_ERROR);

			}        
			return $this->render('PwAccessBundle:Security:login.html.php',
					array('error' => $error, 'last_username' => $session->get(SecurityContext::LAST_USERNAME)));
		}
		return $this->redirect($this->generateUrl('home'));
    }
    
    public function registerAction(Request $request){
		if (!$this->getUser()) {
			$user = new User();
			$form = $this->createForm(new UserType(), $user);
			//$logger = $this->get('logger');
			if ($request->isMethod('POST')) {
				$form->bind($request);
				if ($form->isValid()) {
					$factory = $this->get('security.encoder_factory');
					$encoder = $factory->getEncoder($user);
					$password = $encoder->encodePassword($form->get('password')->getData(), $user->getSalt());
					$user->setPassword($password);
					$em = $this->getDoctrine()->getEntityManager();
					$em->persist($user);
					$em->flush();
					return $this->redirect($this->generateUrl('home'));
				}
			}
			return $this->render('PwAccessBundle:Security:register.html.php',
					array('form' => $form->createView()));
		}
		return $this->redirect($this->generateUrl('home'));
    }
}
